package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 接收自动运维工单
 */
@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
public class VmStatusMsgHandler implements MsgHandler {

    @Resource
    private UserService userService;

    @Resource
    private TaskService taskService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private VMService vmService;


    @Override
    public void process(String jsonMsg) throws IOException {
        if (StringUtils.isEmpty(jsonMsg)) {
            return;
        }
        //解析消息转换成协议类
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (vmStatusContract == null) {
            return;
        }

        //获取消息中状态信息
        vmStatusContract.getStatusInfo().forEach(statusInfo -> {
            //消息中status不为true代表出现故障
            if (!statusInfo.isStatus()) {
                //上报设备状态异常 --- 创建维修工单
                TaskViewModel taskViewModel = new TaskViewModel();
                taskViewModel.setInnerCode(vmStatusContract.getInnerCode());
                taskViewModel.setCreateType(0);
                taskViewModel.setDesc(statusInfo.getStatusCode() + "出现问题，需要维修");
                taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);

                //分配给当前任务数量最少的用户
                //Integer userId = findMinTaskCountUser(vmStatusContract.getInnerCode());
                Integer userId = findMinTaskCountUser(taskViewModel);
                taskViewModel.setUserId(userId);

                taskService.create(taskViewModel);
            }
        });

    }

    /**
     * 查询当前任务数量最少的人员
     *
     * @param taskViewModel
     * @return
     */
    private Integer findMinTaskCountUser(TaskViewModel taskViewModel) {
        //任务执行时间
        String format = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //任务执行区域
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        String roleCode = "1002";
        if (taskViewModel.getProductType() != VMSystem.TASK_TYPE_SUPPLY) {
            roleCode = "1003";
        }

        String key = VMSystem.REGION_TASK_KEY_PREF + format + "." + vmInfo.getRegionId() + "." + roleCode;

        Integer userid = (Integer) redisTemplate.opsForZSet().range(key, 0, 1).stream().findFirst().get();

        return userid;
    }


    /*   *//**
     * 查询当前任务数量最少的人员
     *
     * @param innerCode
     * @return
     *//*
    private Integer findMinTaskCountUser(String innerCode) {
        //查询所有负责该售货机维护的维修人员列表
        List<UserVO> userVOList = userService.getRepairerListByInnerCode(innerCode);

        if (CollectionUtils.isEmpty(userVOList)) {
            throw new LogicException("该区域没有运维人员");
        }

        //查询当天每个维修人员的工单数量
        DateTime begin = DateUtil.beginOfDay(new Date());
        DateTime end = DateUtil.endOfDay(new Date());

        List<TaskEntity> taskEntityList = taskService.getUserTask(begin, end);

        //根据userid进行分组
        Map<Integer, List<TaskEntity>> userCount = taskEntityList.stream().collect(Collectors.groupingBy(TaskEntity::getUserId));

        //从分组中获取工单数最少的人
        List<UserTaskCountVo> countVoList = userVOList.stream().map(userVO -> {

            UserTaskCountVo userTaskCountVo = new UserTaskCountVo();
            userTaskCountVo.setUserId(userVO.getUserId());

            List<TaskEntity> taskList = userCount.get(userVO.getUserId());
            if (CollectionUtils.isEmpty(taskList)) {
                userTaskCountVo.setCount(0);
            } else {
                userTaskCountVo.setCount(taskList.size());
            }
            return userTaskCountVo;
        }).sorted((o1, o2) -> o1.getCount() - o2.getCount()).limit(1).collect(Collectors.toList());


        return countVoList.get(0).getUserId();
    }*/
}
